package org.project.task.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.project.task.common.R;
import org.project.task.common.Search;
import org.project.task.entity.*;
import org.project.task.service.UserService;
import org.project.task.util.JwtUtils;
import org.project.task.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;


    @Autowired
    private PasswordUtil passwordUtil;

    @PostMapping("/getList")
    public R<Page<User>> getList(@RequestBody Search search) {
        try {
            Page<User> pageData = userService.page(
                    getPage(),
                    new QueryWrapper<User>()
                            .like(StrUtil.isNotBlank(
                                            search.getContent()),
                                    "username",
                                    search.getContent()
                            )
                            .or()
                            .like(StrUtil.isNotBlank(
                                            search.getContent()),
                                    "name",
                                    search.getContent()
                            )
                            .orderByDesc("id")
            );
            return new R<Page<User>>().success(pageData);
        } catch (Exception e) {
            return new R<Page<User>>().error(e.getMessage());
        }
    }

    @GetMapping("/userList")
    public R<List<User>> userList() {
        R<List<User>> result = new R<>();
        List<User> userList = userService.list();
        if (userList != null && !userList.isEmpty()) {
            result.success(userList);
        } else {
            result.error("查询对象不存在!");
        }
        return result;
    }


    @PostMapping("/login")
    public R<User> login(@RequestBody User user) {
        R<User> result = new R<>();
        // 使用 md5 加密密码
        String encryptedPassword = passwordUtil.encryptPasswordByMd5(user.getPassword());
        User user_login = userService.login(user.getUsername(), encryptedPassword);
        // 是否存在该用户
        if (user_login != null) {
            // 登录成功后生成token
            user_login.setPassword(encryptedPassword);
            Map<String, Object> claims = new HashMap<>();
            claims.put("username", user_login.getUsername());
            String jwt = JwtUtils.generateJwt(claims);
            user_login.setToken(jwt);
            result.success(user_login);
            result.setMessage("登陆成功！");
        } else {
            result.error("用户不存在/密码错误!");
        }
        return result;
    }


    @GetMapping("/getById/{id}")
    public R<User> getById(@PathVariable("id") Integer id) {
        R<User> result = new R<>();
        User user = userService.getById(id);
        if (user != null) {
            result.success(user);
        } else {
            result.error("查询对象不存在!");
        }
        return result;
    }


    @PostMapping("/delete")
    public R<User> delete(@RequestBody List<Long> ids) {
        R<User> result = new R<>();
        if (userService.removeByIds(ids)) {
            result.success("删除成功！");
        } else {
            result.error("删除失败！");

        }
        return result;
    }


    @PostMapping("/insert")
    public R<User> insert(@RequestBody User user) {
        R<User> result = new R<>();
        if (user != null) {
            if (user.getPassword().isBlank() && user.getPassword().isEmpty()) {
                // 使用 md5 加密密码
                String encryptedPassword = passwordUtil.encryptPasswordByMd5("888888");
                user.setPassword(encryptedPassword);
            } else {
                String encryptedPassword = passwordUtil.encryptPasswordByMd5(user.getPassword());
                user.setPassword(encryptedPassword);
            }
            if (user.getAvatar().isBlank() && user.getAvatar().isEmpty()) {
                user.setAvatar("/images/default.webp");
            }
            boolean rsg = userService.save(user);
            if (rsg) {
                result.success("添加成功！");
                result.setData(user);
            } else {
                result.error("添加失败！");
            }
        } else {
            result.error("请传入正确参数！");
        }
        return result;
    }

    @PostMapping("/register")
    public R<User> register(@RequestBody User user) {
        R<User> result = new R<>();
        if (user != null) {
            String encryptedPassword = passwordUtil.encryptPasswordByMd5(user.getPassword());
            user.setPassword(encryptedPassword);
            user.setAvatar("/images/default.webp");
            user.setName("用户-" + System.currentTimeMillis());
            user.setSex(1);
            boolean rsg = userService.save(user);
            if (rsg) {
                result.success("添加成功！");
                result.setData(user);
            } else {
                result.error("添加失败！");
            }
        } else {
            result.error("请传入正确参数！");
        }
        return result;
    }

    @PostMapping("/update")
    public R<User> update(@RequestBody User user) {
        R<User> result = new R<>();
        if (user != null) {
            User user_ready = userService.getById(user.getId());
            if (!user.getPassword().isEmpty() && !user.getPassword().isBlank()) { // 密码不存在
                // 使用 md5 加密密码
                String encryptedPassword = passwordUtil.encryptPasswordByMd5(user.getPassword());
                user.setPassword(encryptedPassword);
            } else {
                user.setPassword(user_ready.getPassword());
            }
            boolean rsg = userService.updateById(user);
            if (rsg) {
                result.success("修改成功！");
            } else {
                result.error("修改失败！");
            }
        } else {
            result.error("请传入正确参数！");
        }
        return result;
    }

    @PostMapping("/updatePassword")
    public R<User> updatePassword(@RequestBody User user) {
        R<User> result = new R<>();
        if (user != null) {
            String loginPassword = passwordUtil.encryptPasswordByMd5(user.getPassword());
            User user_ready = userService.getOne(
                    new QueryWrapper<User>()
                            .eq("username", user.getUsername())
                            .eq("password", loginPassword)
            );
            if (user_ready == null) {
                result.error("账号/密码有误");
            } else {
                String encryptedPassword = passwordUtil.encryptPasswordByMd5(user.getNewPassword());
                user_ready.setPassword(encryptedPassword);
            }
            boolean rsg = userService.updateById(user_ready);
            if (rsg) {
                result.setData(user_ready);
                result.success("修改成功！");
            } else {
                result.error("修改失败！");
            }
        } else {
            result.error("请传入正确参数！");
        }
        return result;
    }

    @GetMapping("/reset/{id}")
    public R<User> reset(@PathVariable("id") Integer id) {
        R<User> result = new R<>();
        User user = userService.getById(id);
        if (user != null) {
            // 使用 md5 加密密码
            user.setPassword(passwordUtil.encryptPasswordByMd5("888888"));
            boolean rsg = userService.updateById(user);
            if (rsg) {
                result.success("修改成功！");
            } else {
                result.error("修改失败！");
            }
        } else {
            result.error("请传入正确参数！");
        }
        return result;
    }

}
